package search

import (
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"strconv"
	"wechat/global"
	"wechat/handle/model"
)

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
}

var cline = make(map[string]*Node)

type Node struct {
	UserId string
	Conn   *websocket.Conn
	Data   chan []byte
}

func Chat(c *gin.Context) {
	userId := c.Query("userId")
	friendId := c.Query("friendId")
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Println(err)
		return
	}

	if _, ok := cline[userId]; !ok {
		cline[userId] = &Node{
			UserId: userId,
			Conn:   conn,
			Data:   make(chan []byte),
		}
		go ReadMsg(cline[userId], friendId)
		go Send(cline[userId])
	}

}

func ReadMsg(myNode *Node, friendId string) {
	for {
		_, i, err := myNode.Conn.ReadMessage()
		if err != nil {
			log.Println(err)
			return
		}
		friendNode := cline[friendId]
		friendNode.Data <- i
		uid, _ := strconv.Atoi(myNode.UserId)
		fid, _ := strconv.Atoi(friendId)

		var friend model.Friend
		if err = friend.VeryFriend(global.DB, uid, fid); err != nil {
			log.Println("对方不是好友关系")
			return
		}

		var black model.Black
		if err = black.VeryBlack(global.DB, uid, fid); err == nil {
			log.Println("已被拉黑")
			return
		}

	}
}

func Send(myNode *Node) {
	for {
		select {
		case data := <-myNode.Data:
			err := myNode.Conn.WriteMessage(websocket.TextMessage, data)
			if err != nil {
				log.Println(err)
				return
			}
		}
	}
}
